//
//  ViewController.m
//  study
//
//  Created by codew on 5/31/21.
//

#import "ViewController.h"

#import "XYThread.h"

/**
 ====================================================================================
 
                                使用NSPort方式做常驻线程
 
 ====================================================================================
 */

@interface ViewController ()

@property (nonatomic, strong) XYThread * thread;
@property (nonatomic, assign) NSInteger count;

@property (nonatomic, strong) NSPort * port;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.thread = [[XYThread alloc] initWithTarget:self selector:@selector(execute) object:nil];
    [self.thread start];
    
    
}

- (void)execute
{
    self.port = [NSPort port];
    [[NSRunLoop currentRunLoop] addPort:self.port forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
//
    
    
    NSLog(@"runloop 挂了......打印了没?");
}




- (void)methodRun
{
    
    
    self.count++;
    NSLog(@"%s, , 再看看当前线程: %@", __func__, [NSThread currentThread]);
    
    if (self.count == 5) {
        
        
        // 移除 NSPort 并不会停止runloop
//        CFRunLoopRef runLoopRef = CFRunLoopGetCurrent();
//        [[NSRunLoop currentRunLoop] removePort:self.port forMode:NSDefaultRunLoopMode];
        
        
        
        // 干掉线程也能 停掉runloop
        NSLog(@"count: %zd  杀死thread, 停止runloop", self.count);
        [self.thread cancel];
        [NSThread exit];
        self.thread = nil;
        
    }
}





- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self performSelector:@selector(methodRun) onThread:self.thread withObject:nil waitUntilDone:YES];
}


@end
